package com.luoyx.vjsb.common.util;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.codec.binary.Base64;
import sun.misc.BASE64Decoder;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

/**
 * <p>
 *
 * </p>
 *
 * @author luoyuanxiang <p>luoyuanxiang.github.io</p>
 * @since 2020/3/19 16:15
 */
@Slf4j
public class AesUtil {

    private static final String KEY = "QDEAonf1234@#$%^";
    private static final String ALGORITHMIC = "AES/ECB/PKCS5Padding";

    private static String base64Encode(byte[] bytes) {
        return Base64.encodeBase64String(bytes);
    }

    private static byte[] base64Decode(String base64Code) throws Exception {
        return new BASE64Decoder().decodeBuffer(base64Code);
    }

    private static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        Cipher cipher = Cipher.getInstance(ALGORITHMIC);
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));

        return cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
    }

    private static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);

        Cipher cipher = Cipher.getInstance(ALGORITHMIC);
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));
        byte[] decryptBytes = cipher.doFinal(encryptBytes);

        return new String(decryptBytes);
    }

    /**
     * 加密
     *
     * @param content    需要加密的内容
     * @param encryptKey key
     * @return 1
     */
    @SneakyThrows
    public static String aesEncrypt(String content, String encryptKey) {
        return base64Encode(aesEncryptToBytes(content, encryptKey));
    }

    /**
     * 加密
     *
     * @param content 需要加密的内容
     * @return 1
     */
    @SneakyThrows
    public static String aesEncrypt(String content) {
        return base64Encode(aesEncryptToBytes(content, KEY));
    }

    /**
     * 解密
     *
     * @param encryptStr 解密内容
     * @param decryptKey key
     * @return 1
     */
    @SneakyThrows
    public static String aesDecrypt(String encryptStr, String decryptKey) {
        return aesDecryptByBytes(base64Decode(encryptStr), decryptKey);
    }

    /**
     * 解密
     *
     * @param encryptStr 解密内容
     * @return 1
     */
    @SneakyThrows
    public static String aesDecrypt(String encryptStr) {
        return aesDecryptByBytes(base64Decode(encryptStr), KEY);
    }


    public static void main(String[] args) {
        System.err.println(aesEncrypt("KAM+X89IwfQYAShSXFQt/Q==supper_admin"));
    }
}
